/* eslint-disable spaced-comment */
/* eslint-disable no-multi-spaces */
/* eslint-disable eol-last */
/**
 * author: vformAdmin
 * email: vdpadmin@163.com
 * website: https://www.vform666.com
 * date: 2021.08.18
 * remark: 如果要分发VForm源码，需在本文件顶部保留此文件头信息！！
 */

/**
 * afterDev
 * author: YanFormAdmin
 * date: 2025.05.20
 * remark: 借鉴于vform开发的动态表单
 */

import { deepClone, deepChange, $createUid } from "Yan/utils"
import { getDefaultFormConfig } from "Yan/utils/util"
import { layoutSet } from "./components/unit_panel/unitConfig"

function generateId(key = 'unit') {
  return $createUid(8, key, '_')
}

/* 浅拷贝对象属性，obj2覆盖obj1 */
export function overwriteObj(obj1, obj2) {
  Object.keys(obj2).forEach(prop => {
    obj1[prop] = obj2[prop]
  })
}

export default function createDesigner(vueInstance) {
  const defaultFormConfig = deepClone(getDefaultFormConfig())

  return {
    vueInstance: vueInstance,
    designStatus: true,
    previewStatus: false,
    formConfig: getDefaultFormConfig(),
    // 各字段的字典
    fieldLib: {},
    // 表单的树形结构
    fieldTree: [],
    // 编辑已有表单时的缓存
    tempLib: {},
    tempTree: {},
    tempConfig: {},
    // 操作记录
    historyData: {
      index: -1,  //index: 0,
      maxStep: 20,
      steps: [],
    },
    // 当前选中字段
    selectedId: null,
    cssClassList: [],  //自定义样式列表
    uploadBase: '',
    // 工具栏状态控制
    toolbar: {
      undo: true,
      redo: true,
      clear: true,
      importJson: true,
      exportJson: true,
    },
    // 添加入字段字典
    addFieldLib(newCon) {
      // console.log('addFieldLib', newCon.id, { ...this.fieldLib[newCon.id] }, newCon)
      // Object.prototype[newCon.id] = newCon
      this.fieldLib[newCon.id] = newCon
    },
    // saveFieldLib(newCon) {
    //   this.fieldLib[newCon.id] = newCon
    // },
    // 返回某个单元的具体信息
    getFieldLibUnit(id) {
      return this.fieldLib[id]
    },
    // 更新字段字典中的属性值
    setFieldLibOption(newOptions) {
      deepChange(this.fieldLib[this.selectedId].options, newOptions)
      this.emitEvent(`fieldOptionChange_${this.selectedId}`, this.fieldLib[this.selectedId])
      // this.fieldLib[this.selectedId].options = deepClone(newOptions)
      // console.log('setFieldLibOption')
    },
    removeFieldLib(id) {
      delete this.fieldLib[id]
    },
    // 双击添加到编辑器
    addUnitByDbClick(unit) {
      const newCon = this.copyNewFieldUnit(unit)
      // 添加入字段字典
      this.addFieldLib(newCon)
      // this.fieldLib[newCon.id] = newCon
      // 添加入设计树
      if (newCon.group === 'container') this.fieldTree.push({ id: newCon.id, children: [] })
      else this.fieldTree.push(newCon.id)
      this.setSelected(newCon.id)
    },
    // 布局类型 变更
    changeLayoutType(newType) {
      this.formConfig.layoutType = newType
    },
    // 清除已有的配置
    clearDesigner(skipHistoryChange) {
      const emptyWidgetListFlag = this.fieldTree.length === 0
      this.fieldLib = {}
      this.fieldTree = []
      this.selectedId = null
      overwriteObj(this.formConfig, defaultFormConfig) //
      if (skipHistoryChange) {
        //什么也不做！！
      } else if (!emptyWidgetListFlag) {
        this.emitHistoryChange()
      } else {
        this.saveCurrentHistoryStep()
      }
    },
    // 取消当前单元的选中
    clearSelected() {
      this.selectedId = null
      // this.selectedWidgetName = null
      // this.selectedWidget = {}
      // this.selectedWidget = null
    },
    // 将选中的单元参数复制到编辑器
    copyNewFieldUnit(origin) {
      const newCon = deepClone(origin)
      // newCon.id = newCon.id.replace(/-/g, '') + generateId()
      console.log(newCon)
      if (newCon.group === 'container') newCon.id = this.createNewUid('con')
      else newCon.id = this.createNewUid()
      if (newCon.group === 'field') newCon.options.onListener = ''
      // if (newCon.type.indexOf('upload') !== -1) newCon.options.realUploadURL = this.uploadAction
      // newCon.options = Object.assign(newCon.options, layoutSet())
      newCon.options = Object.assign(newCon.options, layoutSet())
      newCon.options.name = newCon.id
      newCon.options.label = newCon.type
      // delete newCon.displayName
      return newCon
    },
    // 创建一个不重复的Id
    createNewUid(key) {
      const a = generateId(key)
      return this.fieldLib[a] ? this.createNewUid(key) : a
    },
    // 导出当前表单配置
    exportJson() {
      const fieldLib = deepClone(this.fieldLib);
      const fieldTree = deepClone(this.fieldTree);
      const formConfig = deepClone(this.formConfig);
      // let fieldParams = this.getLibJson()
      return { fieldLib, fieldTree, formConfig }
    },
    // 获取表单模板
    getImportTemplate() {
      return {
        fieldLib: {},
        fieldTree: [],
        formConfig: deepClone(defaultFormConfig)
      }
    },
    // 布局类型 输出
    getLayoutType() {
      return this.formConfig.layoutType || 'PC'
    },
    // 获取表单填写内容上传时的数据结构
    getLibJson() {
      const JsonObj = {}
      const { fieldLib, fieldTree } = this

      const run = (arr) => {
        arr.forEach(i => {
          const this_lib = typeof i === 'string' ? fieldLib[i] : fieldLib[i.id]
          if (this_lib.group === 'field') {
            if (this_lib.type === 'table') {
              const obj = {}
              this_lib.options.tableCols.forEach(col => {
                const col_lib = fieldLib[col]
                if (col_lib.group === 'field') obj[col] = col_lib.options.defaultValue || null
              })
              JsonObj[i] = [obj]
            } else JsonObj[i] = this_lib.options.defaultValue || null
          } else if (this_lib.group === 'container') {
            run(i.children)
          }
        })
      }
      run(fieldTree)
      return JsonObj
    },
    // 判断是否有参数名
    hasConfig(configName) {
      const originalunit = null
      if (!originalunit || !originalunit.options) {
        return false
      }

      return Object.keys(this.fieldLib[this.selectedId].options).indexOf(configName) > -1
    },
    // 加载导入的表单JSON
    loadFormJson(formJson) {
      let modifiedFlag = false
      this.clearDesigner()
      if (formJson) {
        // this.formWidget.clearWidgetRefList()
        if (formJson.fieldLib) this.fieldLib = formJson.fieldLib
        if (formJson.fieldTree) this.fieldTree.push(...formJson.fieldTree)
        modifiedFlag = true
      }
      if (!!formJson && !!formJson.formConfig) {
        //this.formConfig = importObj.formConfig
        overwriteObj(this.formConfig, formJson.formConfig)  /* 用=赋值，会导致inject依赖注入的formConfig属性变成非响应式 */
        modifiedFlag = true
      }
      if (modifiedFlag) this.emitEvent('form-json-imported', [])  // 通知其他组件
      return modifiedFlag
    },
    // 暂存当前配置
    saveCurrentHistoryStep() {
      this.historyData.steps[this.historyData.index] = deepClone({
        fieldLib: this.fieldLib,
        fieldTree: this.fieldTree,
        formConfig: this.formConfig
      })
      // this.saveFormContentToStorage()
    },
    // 缓存当前配置 刷新后恢复
    // saveFormContentToStorage() {
    //   window.localStorage.setItem('fieldLib_bat', JSON.stringify(this.fieldLib))
    //   window.localStorage.setItem('fieldTree_bat', JSON.stringify(this.fieldTree))
    //   window.localStorage.setItem('formConfig_bat', JSON.stringify(this.formConfig))
    // },
    // 选中了某个表单单元
    setSelected(selected) {
      // console.log('setSelected', selected)
      if (!selected) {
        this.clearSelected()
        return
      }

      // this.selectedWidget = selected
      if (selected) {
        this.selectedId = selected
        console.log('designer selected change =>', selected)
        // this.selectedWidgetName = selected.options.name
      }
    },
    // ------------------ 初始化方法 ------------------ //
    // 初始化编辑器
    initDesigner(resetFormJson) {
      this.fieldLib = {}
      this.fieldTree = []
      this.formConfig = deepClone(defaultFormConfig)
      if (!resetFormJson) this.initHistoryData()
    },
    // ------------------ cssClass方法 ------------------ //
    setCssClassList(cssClassList) {
      this.cssClassList = cssClassList
    },
    getCssClassList() {
      return this.cssClassList
    },
    // ------------------ 操作记录相关 ------------------ //
    // 初始化操作记录
    initHistoryData() {
      this.loadFormContentFromStorage()
      this.historyData.index++
      this.historyData.steps[this.historyData.index] = ({
        fieldLib: deepClone(this.fieldLib),
        fieldTree: deepClone(this.fieldTree),
        formConfig: deepClone(this.formConfig),
      })
    },
    // 读取操作记录中的内容
    runHistoryHandler() {
      this.fieldLib = deepClone(this.historyData.steps[this.historyData.index].fieldLib)
      this.fieldTree = deepClone(this.historyData.steps[this.historyData.index].fieldTree)
      this.formConfig = deepClone(this.historyData.steps[this.historyData.index].formConfig)
    },
    // 撤销上次操作
    undoHistoryStep() {
      // this.toolbar.undo = true
      if (this.historyData.index !== 0) this.historyData.index--
      this.runHistoryHandler()
    },
    // 恢复上次撤销的操作
    redoHistoryStep() {
      // this.toolbar.redo = true
      if (this.historyData.index !== (this.historyData.steps.length - 1)) this.historyData.index++
      this.runHistoryHandler()
    },
    // 更新操作记录
    emitHistoryChange() {
      // console.log('------------', 'Form history changed!')
      if (this.historyData.index === this.historyData.maxStep - 1) this.historyData.steps.shift()
      else this.historyData.index++
      this.historyData.steps[this.historyData.index] = ({
        fieldLib: deepClone(this.fieldLib),
        fieldTree: deepClone(this.fieldTree),
        formConfig: deepClone(this.formConfig),
      })
      // this.saveFormContentToStorage()
      if (this.historyData.index < this.historyData.steps.length - 1) {
        this.historyData.steps = this.historyData.steps.slice(0, this.historyData.index + 1)
      }
      //console.log('history', this.historyData.index)
    },
    // ------------------ 特定方法 ------------------ //
    // 从缓存加载配置
    loadFormContentFromStorage() {
      const fieldLib_bat = window.localStorage.getItem('fieldLib_bat')
      if (fieldLib_bat) this.fieldLib = JSON.parse(fieldLib_bat)
      const fieldTree_bat = window.localStorage.getItem('fieldTree_bat')
      if (fieldTree_bat) this.fieldTree = JSON.parse(fieldTree_bat)
      const formConfigBackup = window.localStorage.getItem('formConfig_bat')
      if (formConfigBackup) overwriteObj(this.formConfig, JSON.parse(formConfigBackup))
      /* 用=赋值，会导致inject依赖注入的formConfig属性变成非响应式 */
    },
    //用于兄弟组件发送事件
    emitEvent(evtName, evtData) {
      vueInstance.$emit(evtName, evtData)
    },
    // 用于兄弟组件接收事件
    handleEvent(evtName, callback) {
      vueInstance.$on(evtName, (data) => callback(data))
    },
  }
}
